import React from 'react';
import { Row, Col, Table, Card, Collapse, Radio, DatePicker, Form, Select, Button, message } from 'antd';
import moment from 'moment';

import HorizontalBarChart from './HorizontalBarChart';
import VerticalBarChart from './VerticalBarChart';
import { DEFAULT_PAGE_SIZE, STAT_BATCH_JOB_ID } from '../../../../utils/constants';
import styles from '../../../common.less';

const Panel = Collapse.Panel;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};
class Statistics extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type: 'auto', // auto manual redo
    };
  }
  componentWillReceiveProps() {
    this.setState({
      type: 'auto',
    });
  }
  getDataSource = (statisticsData = {}) => {
    switch (this.state.type) {
      case 'auto':
        return statisticsData.autoExecutionCharts || {};
      case 'manual':
        return statisticsData.manualExecutionCharts || {};
      case 'redo':
        return statisticsData.redoExecutionCharts || {};
      case 'message':
        return statisticsData.messageExecutionCharts || {};
      default:
        return {};
    }
  };
  handleSearch = () => {
    const { dispatch, form: { validateFields, getFieldsValue } } = this.props;
    validateFields((errors) => {
      if (errors) {
        return;
      }
      const data = getFieldsValue();

      const { jobId, date } = data;
      if (!jobId) {
        message.error('请选择一个BatchJob！');
        return;
      }
      if (!date) {
        message.error('请选择日期！');
        return;
      }
      if (date) data.date = date.format('YYYY-MM-DD');

      dispatch({
        type: 'dataBatchJob/statisticsJob',
        payload: data,
      });
    });
  };
  handleTypeChange = (e) => {
    this.setState({
      type: e.target.value,
    });
  };
  handleJobChange = (value) => {
    localStorage.setItem(STAT_BATCH_JOB_ID, value);
  };
  render() {
    const { jobs, loading, form: { getFieldDecorator }, statistics } = this.props;
    const data = this.getDataSource(statistics.data);
    const {
      totalTransportDataNum,
      totalExecutionNum,
      totalCostTime,
      taskStatistics,
      executionNumbGraph,
      executionTimeGraph,
      taskMaxExecutionTimeGraph,
      taskMinExecutionTimeGraph,
      taskAvgExecutionTimeGraph,
    } = data;

    const tableData = taskStatistics || [];

    const executionNumProps = {
      style: { width: '100%', height: '140px' },
      data: (executionNumbGraph || {}).bars,
      options: {
        barColor: '#ffb039',
        barName: '次数',
      },
    };
    const executionTimeProps = {
      style: { width: '100%', height: '140px' },
      data: (executionTimeGraph || {}).bars,
      options: {
        barColor: '#2b84ff',
        barName: '耗时(毫秒)',
      },
    };
    const taskMaxExecutionTimeProps = {
      style: { width: '100%', height: '300px' },
      data: (taskMaxExecutionTimeGraph || {}).bars,
      options: {
        barColor: '#87ce97',
        barName: '耗时(毫秒)',
      },
    };
    const taskMinExecutionTimeProps = {
      style: { width: '100%', height: '300px' },
      data: (taskMinExecutionTimeGraph || {}).bars,
      options: {
        barColor: '#75D2FF',
        barName: '耗时(毫秒)',
      },
    };
    const taskAvgExecutionTimeProps = {
      style: { width: '100%', height: '300px' },
      data: (taskAvgExecutionTimeGraph || {}).bars,
      options: {
        barColor: '#a569ff',
        barName: '耗时(毫秒)',
      },
    };

    const columns = [
      {
        title: 'TaskID',
        dataIndex: 'taskID',
        key: 'taskID',
      },
      {
        title: 'TaskName',
        dataIndex: 'taskName',
        key: 'taskName',
        width: 200,
      },
      {
        title: '总耗时',
        dataIndex: 'totalCostTime',
        key: 'totalCostTime',
      },
      {
        title: '最长耗时',
        dataIndex: 'maxCostTime',
        key: 'maxCostTime',
      },
      {
        title: '最短耗时',
        dataIndex: 'minCostTime',
        key: 'minCostTime',
      },
      {
        title: '平均耗时',
        dataIndex: 'avgCostTime',
        key: 'avgCostTime',
      },
      {
        title: '传输量',
        dataIndex: 'transportDataNum',
        key: 'transportDataNum',
      },
    ];
    return (
      <div>
        <Row gutter={24} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <RadioGroup onChange={this.handleTypeChange} value={this.state.type}>
              <RadioButton key="0" value="auto">自动</RadioButton>
              <RadioButton key="1" value="manual">手动</RadioButton>
              <RadioButton key="2" value="redo">重试</RadioButton>
              <RadioButton key="3" value="message">消息触发</RadioButton>
            </RadioGroup>
          </Col>
          <Col>
            <div style={{ float: 'right' }}>
              <Form layout="inline">
                <FormItem label="BatchJob" {...formItemLayout} >
                  {getFieldDecorator('jobId', {
                    initialValue: statistics.query.jobId || '',
                    rules: [],
                  })(
                    <Select style={{ width: 300, marginRight: 20 }} onChange={this.handleJobChange}>
                      <Option key="-1" value="">请选择</Option>
                      {
                        jobs.map((item, index) => {
                          return <Option key={index} value={item.id} title={`${item.name}(${item.id})`} >{`${item.name}(${item.id})`}</Option>;
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem label="日期" {...formItemLayout} >
                  {getFieldDecorator('date', {
                    initialValue: statistics.query.date ? moment(statistics.query.date) : null,
                    rules: [],
                  })(
                    <DatePicker />
                  )}
                </FormItem>
                <FormItem label="" {...formItemLayout} >
                  <Button onClick={this.handleSearch}>搜索</Button>
                </FormItem>
              </Form>
            </div>
          </Col>
        </Row>
        <Row gutter={24} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Card loading={loading} className={styles.chartBoard}>
              <p className={styles.chartTitle}>总传输数据量</p>
              <p className={styles.chartContent}>{totalTransportDataNum || '-'}</p>
            </Card>
          </Col>
          <Col span={8}>
            <Card loading={loading} className={styles.chartBoard}>
              <p className={styles.chartTitle}>总执行次数</p>
              <p className={styles.chartContent}>{totalExecutionNum || '-'}</p>
            </Card>
          </Col>
          <Col span={8}>
            <Card loading={loading} className={styles.chartBoard}>
              <p className={styles.chartTitle}>总耗时(毫秒)</p>
              <p className={styles.chartContent}>{totalCostTime || '-'}</p>
            </Card>
          </Col>
        </Row>
        <Row gutter={24} style={{ marginBottom: 16 }}>
          <Col span={12}>
            <Card loading={loading} title="执行次数统计">
              <HorizontalBarChart {...executionNumProps} />
            </Card>
          </Col>
          <Col span={12}>
            <Card loading={loading} title="执行耗时统计(毫秒)">
              <HorizontalBarChart {...executionTimeProps} />
            </Card>
          </Col>
        </Row>
        <Card title="Task统计">
          <Row gutter={24} style={{ marginBottom: 16 }}>
            <Col span={12}>
              <Table
                columns={columns}
                dataSource={tableData}
                loading={loading}
                rowKey={record => record.taskID}
                bordered
                pagination={{
                  pageSize: DEFAULT_PAGE_SIZE,
                }}
              />
            </Col>
            <Col span={12}>
              <Collapse defaultActiveKey={['1']}>
                <Panel header="Task最长耗时统计图" key="1">
                  <VerticalBarChart {...taskMaxExecutionTimeProps} />
                </Panel>
                <Panel header="Task最短耗时统计图" key="2">
                  <VerticalBarChart {...taskMinExecutionTimeProps} />
                </Panel>
                <Panel header="Task平均耗时统计图" key="3">
                  <VerticalBarChart {...taskAvgExecutionTimeProps} />
                </Panel>
              </Collapse>
            </Col>
          </Row>
        </Card>
      </div>
    );
  }
}

export default Form.create()(Statistics);
